package com.yc.damai.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.yc.damai.bean.PageBean;
import com.yc.damai.bean.Product;
import com.yc.damai.bean.Result;
import com.yc.damai.biz.BizException;
import com.yc.damai.biz.ProductBiz;
import com.yc.damai.web.BaseServlet;

@WebServlet("/product/*")
public class ProductServlet extends BaseServlet{

	private static final long serialVersionUID = 1L;
	
	/**
	 * 保存商品 : 新增+修改
	 * 		商品字段属性:
	 * 			新增: id 一定是 null
	 * 			修改: id 非null
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	/**
	 * 业务对象 
	 */
	private ProductBiz pbiz = new ProductBiz();
	
	public void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取商品字段值, 写入到商品对象中
		Product p = new Product();
		p.setPname(request.getParameter("name"));
		
		Result res;
		try {
			BeanUtils.populate(p, request.getParameterMap());
			// 调用业务方法
			pbiz.save(p);
			res = new Result(0, "商品保存成功!");
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
			res = new Result(0, "字段值错误!");
		} catch (BizException e) {
			e.printStackTrace();
			res = new Result(0, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			res = new Result(0, "系统繁忙,请稍后再试");
		} 
		
		// 返回结果
		toJson(response, res);
		
	}
	
	public void page(HttpServletRequest request, HttpServletResponse response) throws IOException, IllegalAccessException, InvocationTargetException {
		PageBean pb = new PageBean();
		BeanUtils.populate(pb, request.getParameterMap());

		Product p = new Product();
		BeanUtils.populate(p, request.getParameterMap());
		
		toJson(response, pbiz.page(p, pb));
	}
	
	
}
